package com.zhaosc.remote.servlet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.ApplicationContext;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zhaosc.configbean.Service;

public class DispatcherServlet extends HttpServlet{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1620440755044954212L;

	protected void service(HttpServletRequest req,HttpServletResponse resp){
		
		try {
			JSONObject requestParam=httpProcess(req, resp);
            String serviceId = requestParam.getString("serviceId");
            String methodName = requestParam.getString("methodName");
            JSONArray paramTypes = requestParam.getJSONArray("paramTypes");
		
            JSONArray methodParamJa=requestParam.getJSONArray("methodParams");
            
            Object[] objs=null;
            
            if(methodParamJa!=null){
            	objs=new Object[methodParamJa.size()];
            	int i=0;
            	for(Object o:methodParamJa){
            		objs[i++]=o;
            	}
            }
            
            ApplicationContext application=Service.getApplication();
            Object serviceBean = application.getBean(serviceId);
	
		Method method=getMethod(serviceBean, methodName, paramTypes);
		
		if(method!=null){
			Object result;
			result=method.invoke(serviceBean, objs);
			
			PrintWriter pw=resp.getWriter();
			pw.write(result.toString());
		
		}else{
			PrintWriter pw=resp.getWriter();
			pw.write("*********no such  method********");
		}
		
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private Method getMethod(Object bean, String methodName,
            JSONArray paramTypes) {
        Method[] methods = bean.getClass().getMethods();
        List<Method> retMethod = new ArrayList<Method>();
        
        for (Method method : methods) {
            //把名字和methodName入参相同的方法加入到list中来
            if (methodName.trim().equals(method.getName())) {
                retMethod.add(method);
            }
        }
        
        //如果大小是1就说明相同的方法只有一个
        if (retMethod.size() == 1) {
            return retMethod.get(0);
        }
        
        boolean isSameSize = false;
        boolean isSameType = false;
        jack: for (Method method : retMethod) {
            Class<?>[] types = method.getParameterTypes();
            
            if (types.length == paramTypes.size()) {
                isSameSize = true;
            }
            
            if (!isSameSize) {
                continue;
            }
            
            for (int i = 0; i < types.length; i++) {
                if (types[i].toString().contains(paramTypes.getString(i))) {
                    isSameType = true;
                }
                else {
                    isSameType = false;
                }
                if (!isSameType) {
                    continue jack;
                }
            }
            
            if (isSameType) {
                return method;
            }
        }
        return null;
	}

	private JSONObject httpProcess(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		StringBuffer sb=new StringBuffer();
		InputStream is=req.getInputStream();
		
		BufferedReader br=new BufferedReader(new InputStreamReader(is, "utf-8"));
		
		String s="";
		while((s=br.readLine())!=null){
			sb.append(s);
		}
		if(sb.toString().length()<=0){
			return null;
		}else{
			return JSONObject.parseObject(sb.toString());
		}
	}
}
